import storeUtils from "utils/StoreUtils";

/** 更改 Vuex 的 store 中的状态的唯一方法是提交 mutation */
const resetState = (state) => {
	state.token = null;
	state.user = {userName: "", permission: 1};
	state.locale = "zh";
	state.isCollapse = false;
	state.envMode = process.env.NODE_ENV;
	state.activeTabValue = "/dashboard";
	state.editableTabs = [{title: "dashboard", name: "/dashboard", icon: "el-icon-s-home", close: null}];
};
//需要持久化的数据保存到项目根目录data下，以json文件形式存储,需要永久存储，且下次APP启动需要取出的，在state中的变量名
let saveKeys = ["menus", "activeTabValue", "editableTabs", "isCollapse", "envMode", "user", "locale"];
// 保存变量到本地存储中,
const saveData = (key, value, state) => {
	// 判断变量名是否在需要存储的数组中
	if (saveKeys.includes(key)) {
		try {
			storeUtils.setStore(key, value);
		} catch (oException) {
			if (oException.name === "QuotaExceededError") {
				console.log("超出本地存储限额！");
				//如果历史信息不重要了，可清空后再设置
				resetData(state);
				storeUtils.setStore(key, value);
			}
		}
	}
};

const resetData = (state) => {
	resetState(state);
	Object.keys(state).forEach(name => {
		saveData(name, state[name], state);
	});
};

const mutations = {
	storeCommit(state, payload) {
		if (Object.keys(state).includes(payload.name)) {
			//退出登录时注销tab, 将 state 初始化原始值
			if (payload.name === "token" && !payload.value) {
				resetData(state);
				return;
			} else {
				// 单层级变量，在state就是一个普通变量的情况
				state[payload.name] = payload.value;
			}
			saveData(payload.name, state[payload.name], state);
		}
		storeUtils.setVuexStore(state);
	}
};

export default mutations;
